/*
 * Copyright (c) 2023 Huawei Technologies Co., Ltd.
 * openUBMC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *         http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

#include <mc/log.h>

#include "interface/optical_module/power.h"

namespace dev {

bool OpticalModule_Power::get_optical_module_power_by_ncsi(uint8_t port_id) {
    ncsi_optical_module_info_t optical_module_info = {};
    bool ret = m_ncsi_over_mctp_huawei->get_optical_module_info(DEFAULT_PACKAGE_ID, port_id,
                                                                &optical_module_info);
    if (!ret) {
        elog("Error: Failed to get optical module power info");
        return false;
    }
    TXOutputPowerMilliWatts.set_value(std::vector<double>(1, optical_module_info.tx_power_milliwatts));
    RXInputPowerMilliWatts.set_value(std::vector<double>(1, optical_module_info.rx_power_milliwatts));
    
    if (optical_module_info.tx_power_upper_threshold_critical != 0xffff) {
        TXPowerUpperThresholdCritical.set_value(
            optical_module_info.tx_power_upper_threshold_critical);
    }
    if (optical_module_info.rx_power_upper_threshold_critical != 0xffff) {
        RXPowerUpperThresholdCritical.set_value(
            optical_module_info.rx_power_upper_threshold_critical);
    }
    
    return true;
}

void OpticalModule_Power::start_ncsi_update_task_huawei(ncsi_over_mctp_hw_ptr ncsi_over_mctp,
                                                         mc::milliseconds      interval,
                                                         uint8_t               port_id) {
    m_ncsi_over_mctp_huawei = ncsi_over_mctp;
    m_ncsi_timer            = new mc::core::timer(this);
    m_ncsi_timer->timeout.connect([this, port_id]() {
        get_optical_module_power_by_ncsi(port_id);
    });
    m_ncsi_timer->set_single_shot(false);
    m_ncsi_timer->start(interval);
}

void OpticalModule_Power::stop_ncsi_update_task() {
    if (m_ncsi_timer) {
        m_ncsi_timer->stop();
        delete m_ncsi_timer;
        m_ncsi_timer = nullptr;
    }
    if (m_ncsi_over_mctp_huawei) {
        m_ncsi_over_mctp_huawei = nullptr;
    }
}

} // namespace dev

MC_REFLECT(dev::OpticalModule_Power)
